package com.youdoneed.user.publicservice;

import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import com.youdoneed.base.pagination.Page;
import com.youdoneed.base.pagination.Paging;
import com.youdoneed.user.application.QueryHelper;
import com.youdoneed.user.model.Location;
import com.youdoneed.user.model.Nation;
import com.youdoneed.user.query.QLocation;
import com.youdoneed.user.query.QNation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;

/**
 * 公共服务实现。
 */
@Service
@Transactional
public class PublicServiceImpl implements PublicService {

    @Autowired
    private SQLQueryFactory queryFactory;

    @Override
    public Page<Nation> getNations(Paging paging) {
        QNation qNation = QNation.Nation;
        SQLQuery<Nation> query = queryFactory.selectFrom(qNation)
                .orderBy(qNation.sorter.asc());
        return QueryHelper.queryPage(paging, query);
    }

    @Override
    public List<Location> subLocations(String parentId) {
        QLocation qLocation = QLocation.Location;
        if (!StringUtils.hasText(parentId)) {
            return Collections.emptyList();
        }
        return queryFactory.selectFrom(qLocation)
                .where(qLocation.parentId.eq(parentId))
                .orderBy(qLocation.sort.asc())
                .fetch();
    }

}
